<template>
  <div id="app-container">
    <!-- 工具条 -->
    <div class="tools-div">
      <el-button
        type="primary"
        size="midium"
        icon="el-icon-upload"
        @click="importData"
      >
        导入Excel
      </el-button>
      <el-button
        type="primary"
        size="midium"
        icon="el-icon-download"
        @click="exportData"
      >
        导出Excel
      </el-button>
      <el-button class="addTopCatalog" type="success" icon="el-icon-plus" size="midium" @click="addCatalog()">添加 一级目录</el-button>
    </div>
    <el-table
      ref="dictTable"
      :data="list"
      border
      row-key="id"
      lazy
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :load="getChildren"
    >
      <el-table-column label="名称" align="left" prop="name" />
      <el-table-column label="编号" prop="id" />
      <el-table-column label="编码" prop="dictCode" />
      <el-table-column label="值" align="left" prop="value" />
      <el-table-column label="创建时间" align="left" prop="createTime" />
      <el-table-column label="更新时间" align="left" prop="updateTime" />
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.type !== 2"
            type="success"
            icon="el-icon-plus"
            size="mini"
            title="添加下级节点"
            @click="add(scope.row)"
          />
          <el-button type="primary" icon="el-icon-edit" size="mini" title="编辑" @click="edit(scope.row)" />
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            title="删除"
            :disabled="scope.row.hasChildren"
            @click="removeDataById(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="数据字典导入" :visible.sync="importDialogVisible" width="30%">
      <el-form>
        <el-form-item label="请选择Excel文件">
          <el-upload
            ref="upload"
            :multiple="false"
            :limit="1"
            :on-exceed="fileUploadExceed"
            :on-success="fileUploadSuccess"
            :on-error="fileUploadError"
            :action="baseApi+importAddress"
            name="file"
            accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <el-button
              type="primary"
              size="small"
              @click="exportTemplate"
            >
              下载模板
            </el-button>
          </el-upload>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog :title="dictInfoDialogTitle" :visible.sync="dictDialogFormVisible">
      <template slot="title">
        <div style="font-size:18px;font-weight: 999; color: midnightblue" v-text="dictInfoDialogTitle">操作提示</div>
      </template>
      <el-form :model="dict">
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="dict.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="编码" :label-width="formLabelWidth">
          <el-input v-model="dict.dictCode" autocomplete="off" />
        </el-form-item>
        <el-form-item label="值" :label-width="formLabelWidth">
          <el-input v-model="dict.value" autocomplete="off" :disabled="valueDisable" />
        </el-form-item>
      </el-form>
      <div v-show="isShowLastCatalog" class="last_catalog">
        <span>上一级目录: </span> <span v-text="lastCatalog" />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dictDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveOrUpdate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api/admin/dict'

export default {
  name: 'List',
  data() {
    return {
      baseApi: process.env.VUE_APP_BASE_API,
      importAddress: '/dict/import',
      exportAddress: '/dict/export',
      templateAddress: '/dict/template',
      list: [],
      importDialogVisible: false,
      dictDialogFormVisible: false,
      nodeInfoMap: new Map(),

      valueDisable: false,
      dictInfoDialogTitle: '',
      formLabelWidth: '60px',
      dict: {
        id: null,
        parentId: null,
        name: '',
        dictCode: '',
        value: '',
        hasChildren: true
      },
      lastCatalog: '',
      isShowLastCatalog: true
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      const { data } = await api.list(1)
      this.list = data
    },
    addCatalog() {
      this.dict = {}
      this.dict.parentId = 1
      this.dictInfoDialogTitle = '添加一级目录'
      this.valueDisable = true
      this.dictDialogFormVisible = true
      this.isShowLastCatalog = false
    },
    // 延迟加载子节点
    getChildren(row, treeNode, resolve) {
      api.list(row.id).then(response => {
        // 负责将子节点数据展示在展开的列表中
        // 追加到当前节点的下一级
        if (response.data.length === 0) {
          // 如果子节点被删完了, 无字节点数据
          // this.list.get("hasChildren") = false
          // row.hasChildren = false
          // window.location.reload()
          this.$set(this.$refs.dictTable.store.states.lazyTreeNodeMap, row.id, response.data)
        } else {
          resolve(response.data)
        }
        resolve(response.data)
        this.nodeInfoMap.set(row.id, { row, treeNode, resolve })
      })
    },
    importData() {
      this.importDialogVisible = true
    },
    // 上传多于一个文件时
    fileUploadExceed() {
      this.$message.warning('只能选取一个文件')
    },

    // 上传成功回调
    fileUploadSuccess(response) {
      if (response.code === 0) {
        this.$message.success('数据导入成功')
        this.importDialogVisible = false
        this.fetchData()
      } else {
        this.$message.error(response.message)
      }
    },
    // 上传失败回调
    fileUploadError(error) {
      this.$message.error('数据导入失败')
      console.log(error)
    },
    exportData() {
      window.location.href = this.baseApi + this.exportAddress
    },
    exportTemplate() {
      window.location.href = this.baseApi + this.templateAddress
    },
    edit(row) {
      api.getById(row.id).then(response => {
        if (row.parentId === '1') {
          this.lastCatalog = ''
          console.log('方法进入')
        } else {
          this.lastCatalog = this.nodeInfoMap.get(row.parentId).row.name
        }
        this.isShowLastCatalog = true
        this.dictInfoDialogTitle = '更新字典信息'
        this.dictDialogFormVisible = true
        this.valueDisable = false
        this.dict = response.data
      })
    },
    saveOrUpdate() {
      if (!this.dict.id) {
        this.save()
      } else {
        this.update()
      }
      this.dictDialogFormVisible = false
    },
    update() {
      api.update(this.dict).then(res => {
        this.$message.success(res.message || '操作成功')
        this.fetchData()
        if (!(this.dict.parentId === '1')) {
          const { row, treeNode, resolve } = this.nodeInfoMap.get(this.dict.parentId)
          this.getChildren(row, treeNode, resolve)
        }
      })
    },
    add(row) {
      this.dict = {}
      this.dictDialogFormVisible = true
      this.dictInfoDialogTitle = '新增字典信息'
      this.isShowLastCatalog = true
      this.dict.parentId = row.id
      this.valueDisable = false
      this.lastCatalog = row.name
    },
    save() {
      api.save(this.dict).then(response => {
        this.$message.success(response.message || '操作成功')
        this.fetchData()
        if (!(this.dict.parentId === '1')) {
          const { row, treeNode, resolve } = this.nodeInfoMap.get(this.dict.parentId)
          this.getChildren(row, treeNode, resolve)
        }
      })
    },
    removeDataById(rowInfo) {
      // debugger
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => { // promise
        // 点击确定，远程调用ajax
        return api.removeById(rowInfo.id)
      }).then((response) => {
        this.$message({
          type: 'success',
          message: response.message
        })
        this.fetchData()
        console.log(typeof rowInfo.parentId)
        if (!(rowInfo.parentId === '1')) {
          const { row, treeNode, resolve } = this.nodeInfoMap.get(rowInfo.parentId)
          this.getChildren(row, treeNode, resolve)
        }
      }).catch((error) => {
        console.log(error)
        this.$message.info('取消删除')
      })
    }
  }
}
</script>

<style scoped>
.el-table {
  width: 95%;
  margin-left: 20px;
  margin-top: 20px;
  margin-right: 20px;
}

.tools-div {
  margin-top: 20px;
  margin-left: 30px;
}
.addTopCatalog {
  float: right;
  margin-right: 100px;
}
.el-col {
  padding-left: 20px;
}

.last_catalog {
  margin-left: 40px;
}
.el-form-item {
  width: 700px;
  margin-left: 20px;
}
.last_catalog span:first-child {
  font-weight: bolder;
}
.last_catalog span:last-child {
  font-weight: bold;
  font-size: 20px;
  color: #1482f0;
}
.my-dialog-title {
  font-weight: bold;
  color: burlywood;
}
</style>
